from PIL import Image
import numpy as np
import cv2
import matplotlib.pyplot as plt

def plot_color_histogram(image_path):
    # 使用Pillow读取图像
    try:
        image = Image.open(image_path)
    except IOError:
        print("图像加载失败")
        return

    # 将图像转换为NumPy数组
    image_np = np.array(image)

    # 检查图像的通道数
    if len(image_np.shape) == 2:
        # 灰度图像
        plt.figure(figsize=(12, 6))
        plt.title('Grayscale Histogram')
        plt.xlabel('Bins')
        plt.ylabel('# of Pixels')
        histogram = cv2.calcHist([image_np], [0], None, [256], [0, 256])
        plt.plot(histogram, color='k')
        plt.xlim([0, 256])
        plt.show()
    elif len(image_np.shape) == 3:
        # 彩色图像，将图像从RGB转换为BGR（OpenCV使用BGR）
        image_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)

        # 创建一个包含三个颜色通道的直方图
        colors = ('b', 'g', 'r')
        plt.figure(figsize=(12, 6))
        plt.title('Color Histogram')
        plt.xlabel('Bins')
        plt.ylabel('# of Pixels')

        # 计算每个颜色通道的直方图
        for i, color in enumerate(colors):
            histogram = cv2.calcHist([image_bgr], [i], None, [256], [0, 256])
            plt.plot(histogram, color=color)
            plt.xlim([0, 256])

        # 显示直方图
        plt.show()
    else:
        print("图像格式不支持")

# 示例调用
image_path = r'D:\develop\PythonCode\python基础\附_项目实战\九_薄膜图片级别分类\data\real_data\level_3\1.tif'
plot_color_histogram(image_path)
